﻿using EncryptAndDecrypt;
using EPlatform_web.App_Start;
using System;
using System.Configuration;
using System.Data;
using System.Web.Mvc;

namespace EPlatform_web.Controllers
{
    public class LoginController : Controller
    {
        /// <summary>
        /// 域，[web.config]
        /// </summary>
        private static readonly string Contract = ConfigurationManager.AppSettings["Contract"];
        private LDAPHelper objldap = new LDAPHelper();
        public ActionResult Login()
        {
            //Session["CONTRACT"] = "";
            Session["Card_No"] = "";
            Session["Name"] = "";
            Session["Dept"] = "";
            Session["DocNo"] = "";
            Session["MacValue"] = "";
            Session["IpAddress"] = "";
            Session["PageIndex"] = "";
            Session["PERMISSIONS"] = "";
            if (Request.Cookies["userName"] == null)
            {
                Response.Cookies["userName"].Value = "";
                Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1).Date;
                Response.Cookies["userName"].Path = "/";
            }
            string querySql = "SELECT E.PAGE_NO, E.PAGE_NAME, E.PAGE_URL, E.PAGE_URL2 FROM ifsapp.ETB_PAGE_INFO_TAB E WHERE E.MENU_GRADE = 1  ORDER BY E.PAGE_NO";
            DataSet dataSet = OracleOperation.QueryData(querySql);
            ViewBag.PageInfo = dataSet.Tables[0].Rows;
            string str = LoginActionValidate();
            if (str == "false")
            {
                return View();
            }
            else
            {
                return Redirect(str);
            }
        }
        public ActionResult UpdatePwd()
        {
            return View();
        }
        [HttpPost]
        public string LoginOn()
        {
            string sqlStr = "";
            string tmpStr = "";
            DataSet dataSet = null;
            string pageIndex = "";//Doc/DocMain
            string userName = Request["userName"].ToString();
            string passWord = Request["passWord"].ToString();
            string page = Request["page"].ToString();
            if (string.IsNullOrEmpty(userName))
            {
                return "{\"flag\":false,\"msg\":\"請輸入用戶名！\"}";
            }
            if (string.IsNullOrEmpty(passWord))
            {
                return "{\"flag\":false,\"msg\":\"請輸入密碼！\"}";
            }
            string enPassword = crypt.Encrypt(passWord);
            sqlStr = "SELECT 1 FROM ifsapp.DOC_USER_TAB A WHERE A.CARD_NO='" + userName + "' AND A.ROWSTATE='Lock' AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
            tmpStr = OracleOperation.GetSelectValue(sqlStr);
            if (!string.IsNullOrEmpty(tmpStr))
            {
                sqlStr = @"SELECT 1
                       FROM ifsapp.DOC_USER_TAB A
                      WHERE A.CARD_NO = '{0}'
                        AND A.ROWSTATE = 'Lock'
                        AND ROUND(TO_NUMBER(SYSDATE - NVL(A.LOCK_DATE, SYSDATE)) * 24 * 60) > 5
                        AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
                sqlStr = string.Format(sqlStr, userName);
                tmpStr = OracleOperation.GetSelectValue(sqlStr);
                if (!string.IsNullOrEmpty(tmpStr))
                {
                    Session["frequency"] = null;
                    sqlStr = " UPDATE ifsapp.DOC_USER_TAB A SET A.ROWSTATE='Normal' WHERE A.CARD_NO='" + userName + "' AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
                    OracleOperation.Exec(sqlStr);
                }
                else
                {
                    return "{\"flag\":false,\"msg\":\"賬號已鎖定，請五分鐘後再試！\",\"reset\":true}";
                }
            }

            sqlStr = "SELECT 1 FROM ifsapp.DOC_USER_TAB A WHERE A.CARD_NO='" + userName + "' AND A.PASSWORD='" + passWord + "' AND A.CARD_NO=A.PASSWORD AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
            tmpStr = OracleOperation.GetSelectValue(sqlStr);
            if (!string.IsNullOrEmpty(tmpStr))
            {
                return "{\"flag\":false,\"msg\":\"首次登陸需修改密碼，請修改密碼！\",\"updatePwd\":true}";
                //跳轉修改密碼
            }

            sqlStr = " SELECT 1 FROM ifsapp.DOC_USER_TAB A WHERE A.CARD_NO='" + userName + "' AND A.PASSWORD<>'" + enPassword + "' AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
            tmpStr = OracleOperation.GetSelectValue(sqlStr);
            if (!string.IsNullOrEmpty(tmpStr))
            {
                if (Session["frequency"] != null)
                {
                    if ((int)Session["frequency"] == 3)
                    {
                        return "{\"flag\":false,\"msg\":\"賬號已鎖定，請五分鐘後再試！\",\"reset\":true}";
                    }
                    else
                    {
                        Session["frequency"] = (int)Session["frequency"] + 1;
                        if ((int)Session["frequency"] == 3)
                        {
                            sqlStr = " UPDATE ifsapp.DOC_USER_TAB A SET A.ROWSTATE='Lock',A.LOCK_DATE=SYSDATE WHERE A.CARD_NO='" + userName + "' AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
                            OracleOperation.Exec(sqlStr);
                        }
                    }
                }
                else
                {
                    Session["frequency"] = 1;
                }

                if ((int)Session["frequency"] == 3)
                {
                    return "{\"flag\":false,\"msg\":\"密碼錯誤，賬號已鎖定，請等待五分鐘後重試！\",\"reset\":true}";
                }
                else
                {
                    return "{\"flag\":false,\"msg\":\"密碼錯誤，請重試,第" + (int)Session["frequency"] + "次失敗，三次後賬號鎖定五分鐘！\"}";
                }
            }

            sqlStr = "SELECT 1 ifsapp.FROM DOC_USER_TAB A WHERE A.CARD_NO = '" + userName + "' AND NVL(TRUNC(SYSDATE) - TRUNC(A.LAST_CHGPWD_DATE), 0) > NVL(A.PWD_CYCLE, 90) AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
            tmpStr = OracleOperation.GetSelectValue(sqlStr);
            if (!string.IsNullOrEmpty(tmpStr))
            {
                return "{\"flag\":false,\"msg\":\"你的密碼已過期，請修改密碼！\",\"updatePwd\":true}";
                //跳轉修改密碼
            }
            try
            {
                sqlStr = @"SELECT A.CONTRACT,
                            A.CARD_NO,
                            A.NAME,
                            A.PASSWORD,
                            A.ROWSTATE,
                            A.LAST_CHGPWD_DATE,
                            A.PWD_CYCLE,
                            A.REMARK,
                            A.LOCK_DATE,
                            A.E_MAIL,
                            A.DEPT_NO,
                            A.PERMISSIONS,
                            A.PAGE_URL2 PAGE_URLS,
                            E.PAGE_URL2 PAGE_URL
                       FROM ifsapp.DOC_USER_TAB A
                       LEFT JOIN ifsapp.ETB_PAGE_INFO_TAB E
                         ON A.CONTRACT = E.CONTRACT
                        AND A.PAGE_NO = E.PAGE_NO
                      WHERE A.CARD_NO = '{0}'
                        AND A.PASSWORD = '{1}'
                        AND A.ROWSTATE = 'Normal'
                        AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
                sqlStr = string.Format(sqlStr, userName, enPassword);
                dataSet = OracleOperation.QueryData(sqlStr);
                if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                {
                    if (page != "00")
                    {
                        pageIndex = page;
                        if (dataSet.Tables[0].Rows[0]["PAGE_URLS"].ToString().IndexOf(pageIndex) < 0)
                        {
                            return "{\"flag\":false,\"msg\":\"你沒有該頁面權限！\"}";
                        }
                    }
                    else if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["PAGE_URL"].ToString()))
                    {
                        pageIndex = dataSet.Tables[0].Rows[0]["PAGE_URL"].ToString();
                    }
                    //Session["CONTRACT"] = dataSet.Tables[0].Rows[0]["CONTRACT"];
                    Session["Card_No"] = dataSet.Tables[0].Rows[0]["CARD_NO"];
                    Session["Name"] = dataSet.Tables[0].Rows[0]["NAME"];
                    Session["Dept"] = dataSet.Tables[0].Rows[0]["DEPT_NO"];
                    Session["PERMISSIONS"] = dataSet.Tables[0].Rows[0]["PERMISSIONS"];
                    Session["DocNo"] = "";
                    Session["MacValue"] = Hpubilc.GetMacValue();
                    Session["IpAddress"] = Hpubilc.GetIpAddress();
                    Session["PageIndex"] = pageIndex;
                    //跳轉首頁
                    sqlStr = @"SELECT NVL(A.PWD_CYCLE, 90) -
                        NVL(TRUNC(SYSDATE) - TRUNC(A.LAST_CHGPWD_DATE), 0) DAYS
                   FROM ifsapp.DOC_USER_TAB A
                  WHERE A.CARD_NO = '{0}'
                    AND (NVL(A.PWD_CYCLE, 90) -
                        NVL(TRUNC(SYSDATE) - TRUNC(A.LAST_CHGPWD_DATE), 0)) BETWEEN 0 AND 3
                    AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
                    sqlStr = string.Format(sqlStr, userName);
                    tmpStr = OracleOperation.GetSelectValue(sqlStr);
                    if (!string.IsNullOrEmpty(tmpStr))
                    {
                        return "{\"flag\":true,\"msg\":\"你的密碼還有" + tmpStr + "天即將過期，請及時修改密碼！\",\"pwdDue\":true,\"pageindex\":\"" + pageIndex + "\"}";
                    }
                    return "{\"flag\":true,\"pageindex\":\"" + pageIndex + "\"}";
                }
                else
                {
                    return "{\"flag\":false,\"msg\":\"賬號或密碼輸入錯誤，請重新輸入！\"}";
                }
            }
            catch (Exception)
            {
                return "{\"flag\":false,\"msg\":\"發生錯誤，請聯繫資訊處理！\"}";
            }
        }
        public string QueryUser()
        {
            try
            {
                string userName = Request["userName"].ToString();
                string querySql = "SELECT 1 FROM ifsapp.DOC_USER_TAB A WHERE A.CARD_NO='" + userName + "'";
                string tmpStr = OracleOperation.GetSelectValue(querySql);
                if (string.IsNullOrEmpty(tmpStr))
                {
                    return "{\"flag\":false,\"msg\":\"賬號不存在！\"}";
                }
                else
                {
                    return "{\"flag\":true}";
                }
            }
            catch (Exception)
            {
                return "{\"flag\":false,\"msg\":\"發生錯誤，請聯繫資訊處理！\"}";
            }
        }
        public string QueryPwd()
        {
            try
            {
                string userName = Request["userName"].ToString();
                string password = Request["password"].ToString();
                string querySql = "SELECT A.PASSWORD FROM ifsapp.DOC_USER_TAB A WHERE A.CARD_NO='" + userName + "'";
                string tmpStr = OracleOperation.GetSelectValue(querySql);
                if (crypt.Encrypt(password) != tmpStr)
                {
                    return "{\"flag\":false,\"msg\":\"舊密碼不正確！\"}";
                }
                else
                {
                    return "{\"flag\":true}";
                }
            }
            catch (Exception)
            {
                return "{\"flag\":false,\"msg\":\"發生錯誤，請聯繫資訊處理！\"}";
            }
        }
        public string Update()
        {
            try
            {
                string userName = Request["userName"].ToString();
                string password = Request["newPassword"].ToString();
                string updateSql = "UPDATE ifsapp.DOC_USER_TAB A SET A.PASSWORD = '" + crypt.Encrypt(password) + "',A.LAST_CHGPWD_DATE = SYSDATE WHERE A.CARD_NO = '" + userName + "' AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
                if (OracleOperation.Exec(updateSql) == 1)
                {
                    return "{\"flag\":true,\"msg\":\"密碼修改成功，請重新登錄！\"}";
                }
                else
                {
                    return "{\"flag\":false,\"msg\":\"密碼修改失敗！\"}";
                }
            }
            catch (Exception)
            {
                return "{\"flag\":false,\"msg\":\"密碼修改失敗！\"}";
            }
        }
        public string SetPage()
        {
            try
            {
                string updateSql = @"UPDATE ifsapp.DOC_USER_TAB
   SET PAGE_NO =
       (SELECT PAGE_NO
          FROM ifsapp.ETB_PAGE_INFO_TAB
         WHERE CONTRACT = '{2}'
           AND PAGE_URL2 = '{1}')
 WHERE CONTRACT = '{2}'
   AND CARD_NO = '{0}'
   AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
                string pageInfo = Request["pageinfo"].ToString();
                string cardNo = Session["Card_No"].ToString();
                if (OracleOperation.Exec(string.Format(updateSql, cardNo, pageInfo, Contract)) == 1)
                {
                    return "{\"flag\":true,\"msg\":\"主頁設置成功！\"}";
                }
                else
                {
                    return "{\"flag\":false,\"msg\":\"主頁設置失敗！\"}";
                }
            }
            catch (Exception)
            {
                return "{\"flag\":false,\"msg\":\"主頁設置失敗！\"}";
            }
        }
        public string Logout()
        {
            Response.Cookies["userName"].Value = null;
            return "{\"flag\":true}";
        }
        public string ResetPwd()
        {
            try
            {
                string userName = Request["userName"].ToString();
                string resetSql = "UPDATE ifsapp.DOC_USER_TAB A SET A.PASSWORD = '" + crypt.Encrypt(userName) + "',A.ROWSTATE='Normal',A.LAST_CHGPWD_DATE = SYSDATE WHERE A.CARD_NO = '" + userName + "' AND NVL(INSTR(A.REMARK, CHR(45233)||CHR(42446)), 0) <= 0";
                if (OracleOperation.Exec(resetSql) == 1)
                {
                    return "{\"flag\":true,\"msg\":\"密碼重置成功，請重新登錄！\"}";
                }
                else
                {
                    return "{\"flag\":false,\"msg\":\"密碼重置失敗，賬號（" + userName + "）不存在！\"}";
                }
            }
            catch (Exception)
            {
                return "{\"flag\":false,\"msg\":\"密碼重置失敗！\"}";
            }
        }
        /// <summary>
        /// 登錄按鈕
        /// </summary>
        public string Validate()
        {
            //LDAPHelper objldap = new LDAPHelper();
            try
            {
                string TestUserID = Request["userName"];
                string TestUserPwd = Request["passWord"];
                if (string.IsNullOrEmpty(TestUserID) || string.IsNullOrEmpty(TestUserPwd))
                {
                    return "{\"flag\":false,\"msg\":\"請輸入用戶名及密碼！\"}";
                }
                string strLDAPFilter = "(&(objectClass=user)(sAMAccountName=" + TestUserID + "))";
                string strLDAPPath = ConfigurationManager.AppSettings["Validate3"];
                string strLDAPAdminName = ConfigurationManager.AppSettings["Validate1"];
                string strLDAPAdminPwd = ConfigurationManager.AppSettings["Validate2"];
                string strMsg = "";
                bool blRet = objldap.OpenConnection(crypt.Decrypt(strLDAPPath), crypt.Decrypt(strLDAPAdminName), crypt.Decrypt(strLDAPAdminPwd));

                if (blRet)
                {
                    blRet = objldap.CheckUidAndPwd(strLDAPFilter, TestUserID, TestUserPwd, ref strMsg);
                    if (blRet)
                    {
                        string pageIndex = "";
                        string page = Request["page"];
                        string sqlStr = @"SELECT A.CONTRACT,
       A.CARD_NO,
       A.NAME,
       A.PASSWORD,
       A.ROWSTATE,
       A.LAST_CHGPWD_DATE,
       A.PWD_CYCLE,
       A.REMARK,
       A.LOCK_DATE,
       A.E_MAIL,
       A.DEPT_NO,
       A.PERMISSIONS,
       A.PAGE_URL2        PAGE_URLS,
       E.PAGE_URL2        PAGE_URL
  FROM ifsapp.DOC_USER_TAB A
  LEFT JOIN ifsapp.ETB_PAGE_INFO_TAB E
    ON A.CONTRACT = E.CONTRACT
   AND A.PAGE_NO = E.PAGE_NO
 WHERE UPPER(A.AD_ACCOUNT) = UPPER('{0}')
   AND NVL(INSTR(A.REMARK, CHR(45233) || CHR(42446)), 0) <= 0"; //UPPER(SUBSTR(A.E_MAIL, 0, INSTR(A.E_MAIL, '@') - 1)) = UPPER('{0}')
                        sqlStr = string.Format(sqlStr, TestUserID);
                        DataSet dataSet = OracleOperation.QueryData(sqlStr);
                        if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                        {
                            if (page != "00")
                            {
                                pageIndex = page;
                                if (dataSet.Tables[0].Rows[0]["PAGE_URLS"].ToString().IndexOf(pageIndex) < 0)
                                {
                                    return "{\"flag\":false,\"msg\":\"你沒有該頁面權限！\"}";
                                }
                            }
                            else if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["PAGE_URL"].ToString()))
                            {
                                pageIndex = dataSet.Tables[0].Rows[0]["PAGE_URL"].ToString();
                            }
                            //Session["CONTRACT"] = dataSet.Tables[0].Rows[0]["CONTRACT"];
                            Session["Card_No"] = dataSet.Tables[0].Rows[0]["CARD_NO"];
                            Session["Name"] = dataSet.Tables[0].Rows[0]["NAME"];
                            Session["Dept"] = dataSet.Tables[0].Rows[0]["DEPT_NO"];
                            Session["PERMISSIONS"] = dataSet.Tables[0].Rows[0]["PERMISSIONS"];
                            Session["DocNo"] = "";
                            Session["MacValue"] = Hpubilc.GetMacValue();
                            Session["IpAddress"] = Hpubilc.GetIpAddress();
                            Session["PageIndex"] = pageIndex;

                            Response.Cookies["userName"].Value = crypt.Encrypt(TestUserID);
                            Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1).Date;
                            Response.Cookies["userName"].Path = "/";
                            //strMsg = "检测用户名" + TestUserID + "和密码" + TestUserPwd + "成功";
                            return "{\"flag\":true,\"pageindex\":\"" + pageIndex + "\"}";
                        }
                        else
                        {
                            return "{\"flag\":false,\"msg\":\"未獲取到此用戶設定！\"}";
                        }
                    }
                    else
                    {
                        //strMsg = "检测用户名" + TestUserID + "和密码" + TestUserPwd + "失败，" + strMsg;
                        return "{\"flag\":false,\"msg\":\"用戶名或密碼錯誤！\"}";
                    }
                }
                else
                {
                    return "{\"flag\":false,\"msg\":\"連接失敗！\"}";
                }
            }
            catch (Exception e)
            {
                Response.Cookies["userName"].Value = null;
                objldap.CloseConnection();
                return "{\"flag\":false,\"msg\":\"" + e.Message + "\"}";
            }
        }
        /// <summary>
        /// LoginActionValidate
        /// </summary>
        public string LoginActionValidate()
        {
            //LDAPHelper objldap = new LDAPHelper();
            try
            {
                if (string.IsNullOrEmpty(Request.Cookies["userName"].Value))
                {
                    return "false";
                }
                else
                {
                    string userName = crypt.Decrypt(Request.Cookies["userName"].Value);
                    string strLDAPFilter = "(&(objectClass=user)(sAMAccountName=" + userName + "))";
                    string strLDAPPath = ConfigurationManager.AppSettings["Validate3"];
                    string strLDAPAdminName = ConfigurationManager.AppSettings["Validate1"];
                    string strLDAPAdminPwd = ConfigurationManager.AppSettings["Validate2"];
                    string strMsg = "";
                    //bool blRet = objldap.OpenConnection(crypt.Decrypt(strLDAPPath), crypt.Decrypt(strLDAPAdminName), crypt.Decrypt(strLDAPAdminPwd));
                    //if (blRet)
                    //{
                        bool blRet = objldap.CheckUidAndPwd(strLDAPFilter, userName, "", ref strMsg);
                        if (blRet)
                        {
                            string pageIndex = "";
                            string sqlStr = @"SELECT A.CONTRACT,
       A.CARD_NO,
       A.NAME,
       A.PASSWORD,
       A.ROWSTATE,
       A.LAST_CHGPWD_DATE,
       A.PWD_CYCLE,
       A.REMARK,
       A.LOCK_DATE,
       A.E_MAIL,
       A.DEPT_NO,
       A.PERMISSIONS,
       A.PAGE_URL2        PAGE_URLS,
       E.PAGE_URL2        PAGE_URL
  FROM ifsapp.DOC_USER_TAB A
  LEFT JOIN ifsapp.ETB_PAGE_INFO_TAB E
    ON A.CONTRACT = E.CONTRACT
   AND A.PAGE_NO = E.PAGE_NO
 WHERE UPPER(A.AD_ACCOUNT) = UPPER('{0}')
   AND NVL(INSTR(A.REMARK, CHR(45233) || CHR(42446)), 0) <= 0"; //SUBSTR(A.E_MAIL, 0, INSTR(A.E_MAIL, '@') - 1) = '{0}'
                            sqlStr = string.Format(sqlStr, userName);
                            DataSet dataSet = OracleOperation.QueryData(sqlStr);
                            if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                            {
                                pageIndex = dataSet.Tables[0].Rows[0]["PAGE_URL"].ToString();
                                //Session["CONTRACT"] = dataSet.Tables[0].Rows[0]["CONTRACT"];
                                Session["Card_No"] = dataSet.Tables[0].Rows[0]["CARD_NO"];
                                Session["Name"] = dataSet.Tables[0].Rows[0]["NAME"];
                                Session["Dept"] = dataSet.Tables[0].Rows[0]["DEPT_NO"];
                                Session["PERMISSIONS"] = dataSet.Tables[0].Rows[0]["PERMISSIONS"];
                                Session["DocNo"] = "";
                                Session["MacValue"] = Hpubilc.GetMacValue();
                                Session["IpAddress"] = Hpubilc.GetIpAddress();
                                Session["PageIndex"] = pageIndex;
                                return pageIndex;
                            }
                            else
                            {
                                return "false";
                            }
                        }
                        else
                        {
                            return "false";
                        }
                    //}
                    //else
                    //{
                    //    return "false";
                    //}
                }
            }
            catch(Exception e)
            {
                Response.Cookies["userName"].Value = null;
                //objldap.CloseConnection();
                return "false";
            }
        }
    }
}